<template>
	<!-- 库存管理 -->
	<view class="stock_control">
		<view class="stockHead">
			<view class="selectEvent">
				<view class="selectButton" @click="isOpenSelect()">
					<img src="@/static/搜索.png" alt="" />
				</view>
				<view class="selectTextInput" v-show="!select.name"><input type="text" v-model="select.data" placeholder=" 设备名称" @input="requestSelect('name')" /></view>
				<view class="selectTextInput" v-show="select.name"><input type="text" v-model="select.data" placeholder="  设备编号" @input="requestSelect('number')" /></view>
				<view class="deleteFont" v-show="select.data != null && select.data != ''" @click="deleteFont()">
					<img src="@/static/取消删除.png" alt="" />
				</view>
			</view>

			<view class="settingButton" @click="settingBoxOpen()" @click.stop="">
				<img src="@/static/更多.png" alt="" />
			</view>
		</view>
		<!-- 更多按钮的菜单 -->
		<view class="settingBox" ref="showPanelTwo" :class="{ isDisplay: isCloseSettingBox }">
			<view class="select-item" @click="addComponentPart">入库</view>
			<view class="select-item" v-show="select.name" @click="selectName('name')">搜索名称</view>
			<view class="select-item" v-show="!select.name" @click="selectName('number')">搜索编号</view>
			<view class="select-item">多选出库</view>
			<view class="select-item">差旅明细</view>
		</view>
		<view class="stockBody">
			<view class="stockCards">
				<view class="stockCards1">
					<view class="font-1">库存价值：</view>
					<view class="font-2">{{ afterTax.toFixed(2) }}￥</view>
				</view>
				<view class="stockCards2">
					<view class="font-1">税额：</view>
					<view class="font-2">{{ warehouse.purchaseContractTax }}￥</view>
				</view>
			</view>
			<view class="stockParts">
				<view class="stockPart" style="margin-bottom: 0rpx; position: sticky; top: 100rpx; z-index: 99; background-color: white; height: 50rpx; font-size: 32rpx">
					<table>
						<tr>
							<td></td>
							<td>编号</td>
							<td>名称</td>
							<td>数量</td>
							<td>价格</td>
							<td>操作</td>
						</tr>
					</table>
				</view>

				<view
					v-for="(item, index) in tableItems"
					:key="index"
					class="stockPart"
					@touchstart="handleTouchStart($event, index)"
					@touchmove="handleTouchMove($event, index)"
					@touchend="handleTouchEnd($event, index)"
					:style="{ transform: `translateX(${item.translateX}rpx)`, transition: item.transition }"
					@click="toComponentsPart(item)"
				>
					<table>
						<tr>
							<td><img src="@/static/元器件.png" alt="" /></td>
							<td>
								<view class="serialNumber">
									{{ item.serialNumber }}
								</view>
							</td>
							<td>
								<view class="name">
									{{ item.name }}
								</view>
							</td>
							<td>
								<view>
									{{ item.number }}
								</view>
							</td>
							<td>
								<view class="cost">{{ item.costFront }}￥</view>
							</td>
							<td class="action-cell">
								<view
									class="action-btn"
									v-if="item.type == 'component'"
									:style="{ backgroundColor: item.isSliding ? '#b1be3d' : '#ff4500' }"
									@click.stop="handleOutStock(item)"
								>
									{{ item.isSliding ? '出库' : '出库' }}
								</view>
								<view class="action-btn" v-else :style="{ backgroundColor: item.isSliding ? '#b1be3d' : '#ff4500' }">
									{{ item.isSliding ? '详情' : '详情' }}
								</view>
							</td>
						</tr>
					</table>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { request } from '../../request';
export default {
	computed: {
		afterTax() {
			return this.warehouse.publicCost + this.warehouse.cashCost + this.warehouse.credit;
		}
	},
	data() {
		return {
			select: {
				nameAddress: null,
				numberAddress: null,
				// 是否搜索名字
				name: false,
				// 搜索内容
				data: null
			},
			// 仓库的信息
			warehouse: {
				purchaseContractTax: null
			},
			// 滑动特效参数
			move: {
				start: {
					x: 0,
					y: 0
				},
				currentIndex: -1
			},
			// 表格数据
			tableItems: [
				{
					serialNumber: null,
					name: null,
					number: null,
					costFront: null,
					translateX: 0,
					transition: 'none',
					isSliding: false
				}
			],
			// 滑动阈值（rpx）
			threshold: 50,
			// 按钮宽度（rpx）
			btnWidth: 220,
			// 功能弹框是否显示
			isCloseSettingBox: true
		};
	},
	methods: {
		// 发送搜索请求
		requestSelect(item) {
			// 创建环境需要的参数
			var data = null;
			let address = null;
			if (item == 'name') {
				address = 'public/selectWarehouseName';
				data = { name: this.select.data };
			} else if (item == 'number') {
				address = 'public/selectWarehouseNumber';
				data = { serialNumber: this.select.data };
			} else {
				console.log('请求错误！');
				return;
			}

			// 等待查询完毕仓库，查询元器件
			request(address, data, 'GET').then((res) => {
				if (res.data.code != 200) {
					this.$message.error('   ' + res.data.msg);
					return;
				}
				this.tableItems = [];

				for (var i = 0; i < res.data.data.length; i++) {
					const data = Object.assign(res.data.data[i], { translateX: 0, transition: 'none', isSliding: true });
					this.tableItems.push(data);
				}
			});
		},
		// 取消文字输入
		deleteFont() {
			this.select.data = null;
			this.requestSelect('name');
		},
		isOpenSelect() {},
		// 切换搜索名字或编号
		selectName(item) {
			if ('name' == item) {
				this.select.name = false;
				console.log('名字');
			} else if ('number' == item) {
				this.select.name = true;
				console.log('编号');
			}
		},
		// 增加元器件
		addComponentPart() {
			uni.navigateTo({
				url: `/pages/inStorage/inStorage?project=${this.warehouse.id}`
			});
		},
		toComponentsPart(item) {
			uni.navigateTo({
				url: `/pages/stockControl/componentsPart?id=${item.id}`
			});
		},
		// // 关闭 设置菜单
		closeShow(e) {
			if (this.$refs.showPanelTwo) {
				this.isCloseSettingBox = true;
			}
		},
		// 打开/关闭设置菜单
		settingBoxOpen() {
			this.isCloseSettingBox = !this.isCloseSettingBox;
		},
		// 触摸开始
		handleTouchStart(event, index) {
			// 记录触摸起始位置
			this.move.start.x = event.touches[0].clientX;
			this.move.start.y = event.touches[0].clientY;
			this.move.currentIndex = index;

			// 重置其他项目的滑动状态
			this.tableItems.forEach((item, i) => {
				if (i !== index) {
					item.translateX = 0;
					item.isSliding = false;
				}
			});
		},

		// 触摸移动
		handleTouchMove(event, index) {
			// 如果不是当前操作的项目，不处理
			if (index !== this.move.currentIndex) return;

			// 计算滑动距离
			const touchX = event.touches[0].clientX;
			const touchY = event.touches[0].clientY;
			const diffX = touchX - this.move.start.x;
			const diffY = touchY - this.move.start.y;

			// 判断是否为横向滑动（水平位移大于垂直位移）
			if (Math.abs(diffX) > Math.abs(diffY)) {
				// 阻止页面滚动
				event.preventDefault();

				// 限制为左滑（只处理负值）
				const translateX = Math.min(0, diffX);

				// 更新当前项目的位置
				this.tableItems[index].translateX = translateX;
				this.tableItems[index].transition = 'none';
				this.tableItems[index].isSliding = Math.abs(translateX) > this.threshold / 2;
			}
		},

		// 触摸结束
		handleTouchEnd(event, index) {
			// 如果不是当前操作的项目，不处理
			if (index !== this.move.currentIndex) return;

			const item = this.tableItems[index];

			// 根据滑动距离决定吸附位置
			if (item.translateX < -this.threshold) {
				// 吸附到完全显示操作按钮的位置
				item.translateX = -this.btnWidth;
				item.isSliding = true;
			} else {
				// 恢复原状
				item.translateX = 0;
				item.isSliding = false;
			}

			// 添加过渡动画
			item.transition = 'transform 0.3s ease';

			// 重置当前操作索引
			this.move.currentIndex = -1;
		},

		// 出库操作
		handleOutStock(item) {
			if (item.isSliding) {
				console.log(`执行出库: ${item.name}`);
				// 这里可以添加实际的出库逻辑
				uni.navigateTo({
					url: `/pages/inStorage/outInventory?id=${item.id}`
				});
			}
		}
	},
	onShow() {
		document.addEventListener('click', this.closeShow);
		// 查询仓库的信息
		request('public/selectWarehouse', {}, 'GET').then((res) => {
			if (res.data.code != 200) {
				this.$message.error('   ' + res.data.msg);
				return;
			}
			this.warehouse = res.data.data;

			// 等待查询完毕仓库，查询元器件
			request('public/selectByProjectToComponent', { projectId: this.warehouse.id }, 'GET').then((res2) => {
				if (res2.data.code != 200) {
					this.$message.error('   ' + res2.data.msg);
					return;
				}
				this.tableItems = [];

				for (var i = 0; i < res2.data.data.length; i++) {
					const data = Object.assign(res2.data.data[i], { translateX: 0, transition: 'none', isSliding: false });
					this.tableItems.push(data);
				}
				// console.log(res2);
			});
		});
	},
	onHide() {
		this.isCloseSettingBox = true;
		// 移除事件监听器，防止内存泄漏
		document.removeEventListener('click', this.closeShow);
	}
};
</script>

<style scoped>
page {
	background-color: white;
	overflow: hidden;
}

/* 隐藏滚动条 */
::-webkit-scrollbar {
	display: none;
}

.stockCards {
	display: flex;
	flex-direction: column;
	justify-content: center;
	/* align-items: center; */
}
.stockCards1 {
	display: flex;
}
.stockCards2 {
	display: flex;
	margin-top: 20rpx;
}
/* .font-2 {
	font-size: 36rpx;
	color: #ff9705;
} */

.stockHead {
	position: fixed;
	width: 100%;
	height: 100rpx;
	background-color: #f5f5f5;
	z-index: 99;
	display: flex;
	align-items: center;
}
.selectEvent {
	position: absolute;
	width: 450rpx;
	/* height: calc(100vh - 100rpx); */
	margin-left: 30rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}
/* 搜索按钮 */
.selectButton {
	position: absolute;
	width: 50rpx;
	height: 50rpx;
	margin-left: -350rpx;
}

.deleteFont {
	position: absolute;
	margin: 13rpx 0 0 750rpx;
}

.deleteFont img {
	width: 60px;
	height: 60px;
}

/* 搜索输入框 */
.selectTextInput {
	position: absolute;
	width: 500rpx;
	margin-left: 220rpx;
	border-radius: 10rpx;
}

/* 设置按钮 */
.settingButton {
	position: absolute;
	width: 50rpx;
	height: 50rpx;
	margin: 0 0 0 680rpx;
}

/* 搜索状态 */
.isOpenSelect {
}

.stockHead img {
	width: 50rpx;
	height: 50rpx;
}

/* 功能菜单 */
.settingBox {
	position: fixed;
	width: 250rpx;
	height: 300rpx;
	background-color: #ffffff;
	margin: 100rpx 0 0 490rpx;
	z-index: 101;
	border: 1rpx solid #a7a7a7;
	box-shadow: 0 2px 3px rgba(168, 168, 168, 1);
}
/* 菜单每一项 */
.select-item {
	width: 100%;
	height: 50rpx;
	margin-top: 20rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}

.isDisplay {
	display: none;
}

.stock_control {
	width: 100%;
	height: 100%;
}
/* 中间的数据 */
.stockBody {
	width: 100%;
	height: auto;
	padding-top: 100rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
}

/* 元器件容器 */
.stockParts {
	width: 700rpx;
	box-sizing: border-box;
	margin-left: 10rpx;
	margin-top: 30rpx;
}

/* 每一条元器件信息 - 优化为卡片式设计 */
.stockPart {
	position: relative;
	width: 130%;
	height: 100rpx;
	padding: 20rpx;
	margin-bottom: 20rpx;
	background-color: #ffffff;
	border-radius: 16rpx;
	box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
	overflow: hidden;
	display: flex;
	justify-content: center;
	align-items: center;
}
table {
	margin-left: -50rpx;
}

tr {
	height: 100rpx;
	max-height: 100rpx;
	display: flex;
	justify-content: center;
	align-items: center;
}
td {
	width: 130rpx;
	height: 100%;
	display: flex;
	align-items: center;
	justify-content: center;
	overflow: scroll;
}
tr td:nth-child(1) {
	max-width: 70rpx;
}
tr td:nth-child(2) {
	width: 150rpx;
}
tr td:nth-child(3) {
	width: 180rpx;
}
tr td:nth-child(4) {
	width: 100rpx;
}
tr td:nth-child(5) {
	width: 140rpx;
}
tr td:nth-child(6) {
	width: 260rpx;
	height: 100%;
}

td view {
	overflow: auto;
}
/* 隐藏滚动条 */
::-webkit-scrollbar {
	display: none;
}

/* 图标 */
.stockPart img {
	width: 50rpx;
	height: 50rpx;
	border-radius: 12rpx;
}

/* 元器件信息区域 */
.stockPart .info {
	flex: 1;
	display: flex;
	flex-direction: column;
	justify-content: center;
}

/* 元器件编号 */
.serialNumber {
	font-size: 26rpx;
	color: #86909c;
	white-space: nowrap;
}

/* 元器件名字 */
.name {
	font-size: 30rpx;
	font-weight: 700;
	color: #1d2129;
	white-space: nowrap;
}

/* 成本价格 */
.cost {
	font-size: 30rpx;
	font-weight: 500;
	color: #ff7d00;
}

/* 库存卡片样式优化 */
.stockCards {
	width: 690rpx;
	height: 280rpx;
	background: linear-gradient(135deg, #1677ff 0%, #0e56c2 100%);
	border-radius: 24rpx;
	box-shadow: 0 10rpx 25rpx rgba(22, 119, 255, 0.2);
	padding: 30rpx;
	color: white;
	position: relative;
	overflow: hidden;
}

/* 卡片背景装饰 */
.stockCards::before {
	content: '';
	position: absolute;
	top: -80rpx;
	right: -80rpx;
	width: 200rpx;
	height: 200rpx;
	background-color: rgba(255, 255, 255, 0.1);
	border-radius: 50%;
}

.stockCards::after {
	content: '';
	position: absolute;
	bottom: -100rpx;
	left: -100rpx;
	width: 240rpx;
	height: 240rpx;
	background-color: rgba(255, 255, 255, 0.05);
	border-radius: 50%;
}

/* 操作按钮 */
.action-btn {
	width: 100%;
	height: 100%;
	padding: 20rpx 0;
	color: white;
	display: flex;
	justify-content: center;
	align-items: center;
	transition: background-color 0.3s;
	margin-left: 75rpx;
}
</style>
